<template>
    <div style="padding: 20px;box-sizing: border-box;background: #fff;">
        <div style="display: flex;justify-content: space-between;">
            <div class="title">
                <div>用户列表</div>
            </div>
            <el-button type="primary" @click="handleAdd" style="margin-bottom: 10px">+ 新增</el-button>
        </div>

        <el-row :gutter="20">
            <el-col :span="5" v-if="treeData.length != 0">
                <div style="background: #fff;height: 80vh;">
                    <avue-tree ref="tree" style="margin-right: 20px;" :option="treeOption"
                        @node-contextmenu="treeNodeContextmenu" :before-open="treeBeforeOpen"
                        :filter="filterNodeMethod" @save="treeSave" @update="treeUpdate" :data="treeData"
                        v-model="treeform" @del="treeDel" @node-click="treeNodeClick">
                    </avue-tree>
                </div>
            </el-col>
            <el-col :span="treeData.length != 0?19:24" style="height: 80vh;">
                <avue-crud :data="data" :option="userOption" @search-change="searchChange" @search-reset="searchReset">
                    <template slot-scope="{row,index}" slot="menu">
                        <el-button type="text" size="small" @click="rowEdit(row,index)">编辑</el-button>

                        <el-button v-if="row.enableFlag" type="text" size="small"
                            @click="rowEnable(row,index)">停用</el-button>
                        <el-button v-else type="text" size="small" @click="rowEnable(row,index)">启用</el-button>

                        <!-- <el-button type="text" size="small" @click="rowPassEdit(row,index)">密码重置</el-button> -->
                        <el-button type="text" size="small" @click="rowDel(row,index)">

                            <div :style="row.enableFlag?'color: #666':''">删除</div>

                        </el-button>
                    </template>

                </avue-crud>
            </el-col>
        </el-row>


        <el-dialog :title="dialogTitle" :visible.sync="userVisible" width="70%" :show-close="false">
            <UserForm v-if="userVisible" @handleClose="handleClose" :defaultFrom="defaultFrom" :dialogType="dialogType">
            </UserForm>
        </el-dialog>
        <el-dialog title="密码重置" :visible.sync="passVisible" width="40%">
            <avue-form ref="passForm" :option="passOption" v-model="passData"></avue-form>
            <div class="sendBtn">


                <el-button @click="passVisible = false">关闭</el-button>
                <el-button type="primary" @click="passConfirm">确认</el-button>

            </div>
        </el-dialog>
    </div>
</template>
<script>
    import userOption from "@/const/mgmt/sys/user";
    import { getUserList, enable, staffDel, staffDetail, staffPassChange } from "@/api/mgmt/sys/user";
    import { orgTree } from "@/api/mgmt/sys/org"

    import UserForm from './UseComponents/UserForm'

    export default {
        components: {
            UserForm
        },
        data() {
            const validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    callback();
                }
            };
            const validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passData.newPassward1) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                userOption: userOption,
                data: [],
                query: {
                    searchContext: '',
                    dept: '',
                    type: ''

                },
                loading: false,
                //新增修改属性
                userVisible: false,
                dialogTitle: '',
                defaultFrom: {
                    mgmtStaffEntity:{
                        clinicId:''
                    }
                },
                dialogType: 'add',
                //重置密码属性
                passVisible: false,
                passData: {},
                passOption: {
                    submitBtn: false,
                    emptyBtn: false,
                    column: [
                        {
                            label: '新密码',
                            prop: 'newPassward1',
                            type: 'input',
                            span: 24,
                            rules: [
                                { required: true, validator: validatePass, trigger: "blur" },
                            ],
                        },
                        {
                            label: '确认密码',
                            prop: 'newPassward2',
                            type: 'input',
                            span: 24,
                            rules: [
                                { required: true, validator: validatePass2, trigger: "blur" },
                            ],
                        }
                    ]
                },
                //左侧树形
                treeData: [],
                treeform: {},
                treeOption: {
                    addBtn:false,
                    menu:false,
                    defaultExpandAll: true,
                    formOption: {
                        labelWidth: 100,
                    },
                    props: {
                        labelText: '标题',
                        label: 'name',
                        value: 'id',
                        children: 'children'
                    }
                },
                deleteFlagVisible: false,
                deleteFlagNotes: '',
                deleteFlagObj: {},
                pid: ''
            }
        },
        mounted() {
            this.treeOnload();
        },
        methods: {
           
            treeNodeClick(data, node, comp) {
                this.query.clinicId = data.id;
                this.onLoad();
                this.defaultFrom.mgmtStaffEntity.clinicId = data.id;
            },

            treeBeforeOpen(done, type) {
                if (['view', 'edit'].includes(type)) {
                    // 查看和编辑逻辑
                    console.log(this.treeform);
                    orgOfficialDetail(this.treeform.id).then((res) => {
                        this.treeform = res.data;
                    })

                } else {

                }
                done()
            },
            treeNodeContextmenu(data, node, comp) {
                this.treeform = data;
            },
            filterNodeMethod(value, data) {
                console.log(value, data)
                return !value || data.label.indexOf(value) !== -1
            },
            treeSave(parent, data, done, loading) {
                this.treeform.offcialPid = 1;
                orgOfficialAdd(this.treeform).then(res => {
                    this.$message.success("新增成功");
                    this.onLoad();
                    done();
                })
            },
            treeUpdate(parent, data, done, loading) {
                orgOfficialUpdata(this.treeform).then(res => {
                    this.$message.success("修改成功");
                    this.onLoad();
                    done();
                })

            },
            treeDel() {
                this.rowDel(this.treeform, true)
            },
            passConfirm() {
                console.log(this.passData)
                this.$refs.passForm.validate((valid, done, msg) => {

                    if (valid) {
                        staffPassChange(this.passData).then((res) => {
                            console.log('ren');
                            if (res.success) {
                                this.$message({
                                    type: "success",
                                    message: "操作成功!"
                                });
                                this.passVisible = false;
                                this.$refs.passForm.resetForm();
                                this.onLoad();
                                done()
                            } else {
                                this.$message({
                                    type: "error",
                                    message: res.message
                                });
                                done()
                            }

                        })

                    }
                })
            },
            rowPassEdit(row) {

                this.passData.userId = row.id;
                this.passVisible = true;
            },
            rowEnable(row) {
                this.$confirm(row.enableFlag ? '是否确认停用?' : '是否确认启用?', {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {

                        enable(row.id).then(res => {
                            if (res.success) {
                                this.$message({
                                    type: "success",
                                    message: "操作成功!"
                                });
                                this.onLoad();
                            }

                        })

                    })


            },
            rowDel(row) {
                if (row.enableFlag) {
                    return;
                }
                this.$confirm('是否确认删除?', {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                })
                    .then(() => {

                        staffDel(row.id).then(res => {
                            if (res.success) {
                                this.$message({
                                    type: "success",
                                    message: "操作成功!"
                                });
                                this.onLoad();
                            }

                        })

                    })
            },
            handleClose(type) {
                this.userVisible = false;
                if (type) {
                    this.onLoad();
                }

            },
            handleAdd() {
                this.dialogTitle = '员工信息新增';
                this.dialogType = 'add'
                this.userVisible = true;

            },
            rowEdit(row) {
                this.dialogType = 'edit'
                this.dialogTitle = '员工信息修改'
                staffDetail(row.id).then((res) => {

                    this.defaultFrom = res.data;
                    setTimeout(() => {
                        this.userVisible = true;

                    }, 50)

                })


            },
            searchReset() {
                this.query = {};
                this.onLoad();
            },
            searchChange(params, done) {
                this.query = params;
                this.onLoad(params);
                done();
            },
            onLoad() {

                this.loading = true;
                this.query._page = 1;
                this.query._limit = 100000;
                

                getUserList(this.query).then(res => {
                    this.data = res.list;
                    this.loading = false;
                })

                

            },
            treeOnload() {
                
                orgTree({
                    searchType: 1,
                    searchContent: this.query.searchContent,
                }).then(res => {
                    this.query.clinicId = res.list[0].id;
                    res.list.shift();
                    // 按 type 字段分组
                    let data = res.list.reduce((acc, item) => {
                        if (!acc[item.type]) {
                        acc[item.type] = [];
                        }
                        acc[item.type].push(item);
                        return acc;
                    }, {});

                    this.treeData =  Object.values(data[1] || {});
                    
                    this.onLoad();
                })
            },
            buildTree(list, idKey = 'id', pidKey = 'pid', rootPid = null) {
                return list.filter(item => item[pidKey] === rootPid).map(item => {
                    const children = this.buildTree(list, idKey, pidKey, item[idKey]);
                    if (children.length) {
                        item.children = children;
                    }
                    return item;
                });
            },

        }



    }
</script>
<style scoped>
    .title {
        padding-left: 10px;
        border-left: 4px solid #DC402B;
        margin-bottom: 22px;
    }

    .sendBtn {
        margin: 0px auto 0;
        display: flex;
        justify-content: center;
    }
</style>